import pandas as pd

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['font.sans-serif'] = ['SimHei']
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Cluster 0: [1.91472868 3.53488372 1.41085271 2.28682171 1.82945736]
# Cluster 1: [3.5503876  2.71317829 4.78294574 3.13953488 1.81395349]
# Cluster 2: [3.94573643 2.28682171 9.70542636 3.07751938 2.17829457]
# 读取包含 KMeans 标签和输入变量的文件
df_with_labels = pd.read_csv("new_file_with_kmeans_labels.csv")

# 获取输入变量列
input_variables = ['Q2','Q3','Q4','Q5','Q6','Q10','Q11','Q12','Q13','Q14']

# 按照 KMeans 标签分组，并计算每个变量在每个聚类中的平均值
cluster_means = df_with_labels.groupby('tKMeans_Label')[input_variables].mean()

# 将变量名称替换为中文
variable_names = {
    'Q2': '性别',
    'Q3': '年龄',
    'Q4': '学历',
    'Q5': '职业',
    'Q6': '可支配收入',
    'Q10': '了解程度',
    'Q11': '购买意愿',
    'Q12': '尝试购买',
    'Q13': '意义',
    'Q14': '宣传'
}

# 遍历每个聚类并绘制单独的图表
for label, data in cluster_means.iterrows():
    # 替换变量名
    data.index = [variable_names[var] for var in data.index]

    # 设置图形大小
    plt.figure(figsize=(10, 6))

    # 绘制条形图
    sns.barplot(x=data.values, y=data.index, palette='viridis')

    # 添加标题和标签
    plt.title(f'Cluster {label} 输入变量重要性')
    plt.xlabel('变量重要性指标')
    plt.ylabel('变量')

    # 保存图像到文件
    plt.savefig(f'cluster_{label}_input_variable_importance.png', dpi=300)

    # 显示图形
    plt.show()
